import { getToken, setToken, removeToken } from "chaos-sso-util";
import { logout, getInfo } from "@/api/login";
const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
    userInfo: {},
    approvalCount: {
      MY_CC: 0, //抄送
      MY_DID: 0, //已处理
      MY_DO: 0, //未处理
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER_INFO: (state, { userInfo }) => {
      state.userInfo = userInfo;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_APPROVAL_COUNT: (state, approvalCount) => {
      state.approvalCount = approvalCount;
    },
  },
  actions: {
    //获取流程数量
    setApprovalCount({ commit }, approvalCount) {
      commit("SET_APPROVAL_COUNT", approvalCount);
    },
    // 登录
    Login({ commit }, token) {
      commit("SET_TOKEN", token);
      setToken(token);
    },
    // 登录
    setPermission({ commit }, permissions) {
      commit("SET_PERMISSIONS", permissions);
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token)
          .then((res) => {
            const data = res.data;
            commit("SET_USER_INFO", { userInfo: data });
            const user = data.user;
            const avatar =
              user.hasOwnProperty("avatar") && user.avatar == ""
                ? require("@/assets/profile.jpg")
                : user.avatar;
            if (data.roles && data.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", data.roles);
              commit("SET_PERMISSIONS", data.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_NAME", user.userName);
            commit("SET_AVATAR", avatar);
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            commit("SET_USER_INFO", {});
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        commit("SET_PERMISSIONS", []);
        commit("SET_USER_INFO", {});
        removeToken();
        resolve();
      });
    },
  },
};
export default user;
